@ECHO OFF
SETLOCAL

REM 设置当前脚本所在的目录为变量
SET "SCRIPT_DIR=%~dp0"

REM 调用Visual Studio 2017 Enterprise的vcvarsall.bat来设置环境变量
CALL "%ProgramFiles(x86)%\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x64
IF %ERRORLEVEL% NEQ 0 (
    ECHO Failed to set up Visual Studio 2017 Enterprise environment
    PAUSE
    EXIT /B 1
)

REM 将Python2.7.18和Scripts目录添加到PATH
SET "PATH=%SCRIPT_DIR%Python2.7.18;%SCRIPT_DIR%Python2.7.18\Scripts;%PATH%"

REM 检查Python是否可用
python -V
IF %ERRORLEVEL% NEQ 0 (
    ECHO Python is not available. Please check your Python installation.
    PAUSE
    EXIT /B 1
)

REM 将Ruby33-x64目录添加到PATH
SET "PATH=%SCRIPT_DIR%Ruby33-x64\bin;%PATH%"

REM 检查Ruby是否可用
ruby -v
IF %ERRORLEVEL% NEQ 0 (
    ECHO Ruby is not available. Please check your Ruby installation.
    PAUSE
    EXIT /B 1
)

REM 将Strawberry Perl相关的目录添加到PATH
SET "PATH=%SCRIPT_DIR%Strawberry5.38.2.2\c\bin;%SCRIPT_DIR%Strawberry5.38.2.2\perl\site\bin;%SCRIPT_DIR%Strawberry5.38.2.2\perl\bin;%PATH%"

REM 检查Perl是否可用
perl -v
IF %ERRORLEVEL% NEQ 0 (
    ECHO Perl is not available. Please check your Perl installation.
    PAUSE
    EXIT /B 1
)

REM 将jom的目录添加到PATH
SET "PATH=%SCRIPT_DIR%jom;%PATH%"

REM 输出更新后的PATH以确认
ECHO Updated PATH: %PATH%

REM 切换到Qt源码目录
CD /D "%SCRIPT_DIR%qt-everywhere-src-5.14.2"
IF %ERRORLEVEL% NEQ 0 (
    ECHO Failed to change directory to qt-everywhere-src-5.14.2
    PAUSE
    EXIT /B 1
)

REM 定义构建目录
SET "BUILD_DIR=%SCRIPT_DIR%build\qt_5.14.2_msvc2017x64_static"

REM 创建构建目录（如果不存在）
IF NOT EXIST "%BUILD_DIR%" MKDIR "%BUILD_DIR%"

REM 切换到构建目录
CD /D "%BUILD_DIR%"
IF %ERRORLEVEL% NEQ 0 (
    ECHO Failed to change directory to %BUILD_DIR%
    PAUSE
    EXIT /B 1
)

REM 配置Qt，同时编译Release和Debug版本，并指定OpenSSL路径
"%SCRIPT_DIR%qt-everywhere-src-5.14.2\configure" -prefix "%SCRIPT_DIR%install\qt_5.14.2_msvc2017x64_static" -debug-and-release -opensource -confirm-license -static -nomake examples -nomake tests -platform win32-msvc -I "%SCRIPT_DIR%install\OpenSSL_1_1_1dx64_static\include" -L "%SCRIPT_DIR%install\OpenSSL_1_1_1dx64_static\lib" -plugin-sql-sqlite -plugin-sql-odbc -qt-zlib -qt-libpng -qt-libjpeg -skip qttexttospeech -skip qtspeech -skip qdoc -skip webengine
IF %ERRORLEVEL% NEQ 0 (
    ECHO Configuration failed
    PAUSE
    EXIT /B 1
)

REM 使用jom进行并行编译
jom -j 8
IF %ERRORLEVEL% NEQ 0 (
    ECHO jom failed
    PAUSE
    EXIT /B 1
)

REM 安装Qt
nmake install
IF %ERRORLEVEL% NEQ 0 (
    ECHO Installation failed
    PAUSE
    EXIT /B 1
)

ECHO Qt 5.14.2 (both Release and Debug) has been successfully built and installed.

REM 清理构建目录
ECHO Cleaning up build directory...
CD /D "%SCRIPT_DIR%"
RD /S /Q "%BUILD_DIR%"
IF %ERRORLEVEL% NEQ 0 (
    ECHO Failed to clean up build directory
    PAUSE
    EXIT /B 1
)

ECHO Build directory cleaned up successfully.
PAUSE
ENDLOCAL